import {ChangeDetectorRef, Component} from '@angular/core';
import {
    AlertController, IonicPage, NavController, NavParams, Platform, LoadingController,
    ToastController
} from 'ionic-angular';
import {} from "../../../model/pages/client/insured-client-detail/insured-client-detail.model";
import {CallNumber} from "@ionic-native/call-number";
import {ScheduleStrResourceCh} from "../../../model/pages/schedule/schedule-add/schedule-add.model";
import {InsuredClientDetailProvider} from "../../../providers/client/insured-client-detail/insured-client-detail.provider";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {ClientData} from "../../../model/pages/client/holder-client-detail/holder-client-detail.model";
import {BaseInfo} from '../../../model/pages/client/client-detail/client-detail-main.model';
import {HolderClientDetailProvider} from "../../../providers/client/holder-client-detail/holder-client-detail.provider";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {EmptyAddress, InType, Child} from "../../../model/pages/client/client-detail/client-detail-main.model";
import {FavoriteListProvider} from "../../../providers/client/favorite-list/favorite-list.provider";
import * as moment from "moment";
import {ProgressSearch} from "../../../model/pages/client/client-note/client-note-list/client-note-list.model";
import {ClientNoteListProvider} from "../../../providers/client/client-note/client-note-list/client-note-list.provider";
import {LoadingService} from '../../../services/common/loading.service';
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {ClientMapProvider} from "../../../providers/client/client-map/client-map.provider";
import {ToastService} from '../../../services/common/toast.service';

@IonicPage()
@Component({
    selector: 'page-insured-client-detail',
    templateUrl: 'insured-client-detail.html',
    providers: [
        CallNumber,
        InsuredClientDetailProvider,
        ClientNoteEditProvider,
        FavoriteListProvider,
        ClientNoteListProvider,
        LoadingService,
        CallNumberService,
        ClientMapProvider,
        ToastService
    ]
})

export class InsuredClientDetailPage {
    // 客户其他信息是否展开
    private otherInfoOpenStatus: boolean = false;
// 客户详情信息收起展开
    private openMsgStatus: boolean = false;
    // 标记是否收藏
    private collectStatus: boolean = false;
    // 中心信息切换
    private messageType: number;
    // 当前客户id
    private clientId: number;
    // 客户头像
    private clientAvatar: string;
    // 是否进入页面状态
    private inPageStatus: boolean;
    // 用于全局控制弹窗的对象
    private alertObj;
    // 页面提示
    private curStrResource = ScheduleStrResourceCh;
    // 当前clientNum
    private currentClientNum: any;
    // 当前客户电话列表
    private phoneList: any = [];
    // 客户等级class
    private levelClass: string = '';
    // 空字符数组
    private spareArr: string[] = [''];
    // 是否同时为被保人
    private sameAsInsured: boolean;
    // 新的客户详情对象
    private clientsData: any = {};
    // 子女模型
    private child = Child;
    // 加载等待
    private loading: any;
    // 空地址
    private emptyAddress = EmptyAddress;
    // 购买类型
    private inType = InType;
    //是否在收藏夹中
    private isFavorited: boolean = false;
    //初始收藏状态
    private oldFavorited: boolean = false;
    // 客户跟进请求对象
    private getProgress:ProgressSearch=new ProgressSearch();
    // 客户跟进数据
    progressList:any[]=[];

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public platform: Platform,
                public alertCtrl: AlertController,
                public loadCtr: LoadingController,
                public callNumber: CallNumber,
                public ref: ChangeDetectorRef,
                public clientDetailProvider: InsuredClientDetailProvider,
                public favoriteListProvider: FavoriteListProvider,
                public toastCtrl: ToastController,
                public clientNoteEditProvider: ClientNoteEditProvider,
                public clientNoteListProvider:ClientNoteListProvider,
                private callNumberService: CallNumberService,
                public loadingService:LoadingService,
                public  map: ClientMapProvider,
                public toastService:ToastService
                ) {
    }

    goMap(){
        let goMapMsg,latitude,longitude;
        if(!this.clientsData || !this.clientsData.addressList || !this.clientsData.addressList.length){
            goMapMsg = '没有默认地址';
        }else
        {
            const defaultAddr = this.clientsData.addressList.filter(add => add.defaultIndicator == 1);

            if (defaultAddr.length) {
                if (defaultAddr[0].locationLatitude && defaultAddr[0].locationLongitude) {
                    latitude = defaultAddr[0].locationLatitude;
                    longitude = defaultAddr[0].locationLongitude;
                }
                goMapMsg = '';
                this.navCtrl.push('ClientBMapPage', {
                    id: this.clientsData.leadId,
                    type: 2,           //1准客户,2核心客户
                    address:defaultAddr[0].address,
                    latitude:latitude,
                    longitude:longitude,
                    clientRole:this.clientsData.clientRole
                });
            } else {
                goMapMsg = '默认地址无法定位';
            }
            if (goMapMsg) {
                let toast = this.toastCtrl.create({
                    message: goMapMsg,
                    position: 'middle',
                    duration: 1200
                });
                toast.present();
            }
        }
    }

    ionViewDidLoad() {
        // 初始化信息
        this.initData();
        // 填充信息
        this.navParams.get('role') == 'I' ? this.sameAsInsured = true : this.sameAsInsured = false;
        this.currentClientNum = this.navParams.get('clientNum');
        console.log(this.currentClientNum);
        this.messageType = 1;
        this.getClientDetailData();
    }

    ionViewDidEnter() {
        this.inPageStatus = true;
        let flag = MessageBushService.getMessage(MessageBushService.keys.clientDetailDataUpdated);
        if (flag == "1") {
            MessageBushService.setMessage(MessageBushService.keys.clientDetailDataUpdated, "0");
            this.getClientDetailData();
        }
        // 跟进
        this.getProgress.clientId=this.currentClientNum;
        this.getProgress.clientType=2;
        this.getProgress.limit=3;
        this.getProgressList();
    }

    ionViewWillLeave() {
        this.inPageStatus = false;
    }

    // 初始化
    initData() {
        this.clientsData.address = '';
        this.clientsData.addressList = [''];
        this.clientsData.age = '';
        this.clientsData.birthDate = '';
        this.clientsData.clientId = '';
        this.clientsData.clientRole = '';
        this.clientsData.deathFlag = '';
        this.clientsData.email = '';
        this.clientsData.idExpiryDate = '';
        this.clientsData.idNum = '';
        this.clientsData.idType = '';
        this.clientsData.income = '';
        this.clientsData.mobilePhone = '';
        this.clientsData.name = '';
        this.clientsData.occupation = '';
        this.clientsData.payToDate = '';
        this.clientsData.mobileList = [''];
        this.clientsData.policyNum = '';
        this.clientsData.premium = '';
        this.clientsData.sexCode = '';
        this.clientsData.totalPolicy = '';
        this.clientsData.vipFlag = '';
        this.clientsData.zipCode = '';
        this.clientsData.zipCodeList = [''];
        this.clientsData.totalClaim = '';
        this.clientsData.occupationType = '';
    }

    /**
     *  生日格式化
     */
    birthFormat(str) {
        const result = moment(str).format('YYYY/MM/DD');
        if (result != 'Invalid date') {
            return result;
        } else {
            return '';
        }
    }

    /**
     * 跳转到人工线索
     */
    goToleadsList(a) {
        if (a == "人工线索") {
            this.navCtrl.push("ClientNoteListPage", {"clientNum": this.clientsData.clientId, "tabName": "cule"})
        }
    }

    /**
     * 跳转到保单详情
     */
    goToPolicyDetail(num){
        if(Number(num)){
            this.navCtrl.push('ClientPolicyListPage',{"clientNum":this.clientsData.clientId})
        }
    }

    /**
     * 跳转到理赔列表
     */
    goToClientClaim(num) {
        if(Number(num)){
            this.navCtrl.push('ClientClaimPage', {'clientNum': this.clientsData.clientId});
        }
    }

    /**
     * 销售线索展示
     */
    public leadsList = [];

    getLeadsList(list) {
        this.leadsList = [];
        let length = 188 + 50;
        for (let i = 0; i < list.length; i++) {
            length += (list[i].length * 42 + 32 + 10);
            this.leadsList.push(window['unescape'](list[i].replace(/\\u/g, '%u')));
            if (length >= window.innerWidth) {
                break;
            }
        }
    }

    /**
     * 切换其他信息展开状态
     */
    changeOtherInfoOpenStatus() {
        this.otherInfoOpenStatus = !this.otherInfoOpenStatus;
        this.ref.detectChanges();
    }

    private getMarriageType() {
        if (!this.clientsData.marriageType)
            return "未知";
        if (this.clientsData.marriageType == 1)
            return "已婚";
        if (this.clientsData.marriageType == 2)
            return "未婚";
        if (this.clientsData.marriageType == 3)
            return "其他";
    }

    // 身份证时间验证
    checkIdDate(idDate) {
        if (idDate && idDate === "9999-12-31") {
            return "长期有效";
        } else if (!idDate) {
            return "";
        } else {
            return idDate;
        }
    }

    // 切换信息类型
    transMessage(num) {
        this.messageType = num;
    }

    // 获取客户详情
    getClientDetailData() {
        this.loadingService.showLoading();
        this.clientDetailProvider.getClientDetailData(this.currentClientNum).subscribe((res) => {
            this.loadingService.dismissLoading();

            //加载销售线索
            this.getLeadsList(res.tagList);
            if (res && res.name) {
                this.clientsData = res;
                this.phoneList = this.clientsData.mobilePhone;
                // 获取客户头像
                this.clientAvatar = HolderClientDetailProvider.getClientAvatar(this.clientsData);
                // 获取客户等级
                this.levelClass = String(this.getClientLevel(this.clientsData.vipFlag ? this.clientsData.vipFlag : 'X'));
                //地址
                if(res.addressList.length){
                    for(let i=0;i<res.addressList.length;i++){
                        res.addressList[i].address = res.addressList[i].address.toUpperCase();
                        if(res.addressList[i].defaultIndicator == 1){
                            this.map.updatePoiByClientId(res.addressList[i].address,res.clientId,2).subscribe(res=>{
                            });
                        }
                    }
                }
            } else {
                this.toastService.showToast('请求数据为空');
            }
            this.isFavorited = this.clientsData.favorite;
            this.oldFavorited = this.clientsData.favorite;
        }, err => {
            this.loadingService.dismissLoading();
        });
    }

    // 获取跟进
    getProgressList(){
        this.clientNoteListProvider.getProgressList(this.getProgress).subscribe((res)=>{
            this.progressList=res['notes']
        })
    }

    // 点击收藏
    collectClickHandle() {
        let status = '0';
        if (this.isFavorited) {
            this.favoriteListProvider.removeFromFavorite(this.currentClientNum).subscribe((res) => {
                this.isFavorited = !this.isFavorited;
                this.toastService.showToast('取消收藏成功！');

                if (this.isFavorited == !this.oldFavorited) {
                    status = '1';
                } else {
                    status = '0';
                }
                MessageBushService.setMessage(MessageBushService.keys.favoriteIsUpdated, status);
            });
        } else {
            this.favoriteListProvider.addToFavorites(this.currentClientNum, '2').subscribe((res) => {
                this.isFavorited = !this.isFavorited;
                this.toastService.showToast('收藏成功！');

                if (this.isFavorited == !this.oldFavorited) {
                    status = '1';
                } else {
                    status = '0';
                }
                MessageBushService.setMessage(MessageBushService.keys.favoriteIsUpdated, status);
            });
        }
    }

    // 删除客户
    deleteClient() {
        this.showConfirm('确定删除客户？',
            () => {
                this.deleteClientRequest();
            },
            () => {
            });
    }

    // 删除客户请求
    deleteClientRequest() {
        this.clientDetailProvider.deleteClient(this.currentClientNum).subscribe((res) => {
            if (res) {
                this.navCtrl.pop();
            }
        })
    }


    // 拨打电话
    callPhone(phoneNumber) {
        if (!this.platform.is('cordova')) {
            return false;
        }
        this.callPhoneNumber(phoneNumber);
    }

    // 单个电话拨打
    onePhoneCall() {
        if (!this.platform.is('cordova')) {
            return false;
        }
        if (this.phoneList.length > 0 && this.phoneList[0] && this.phoneList[0].mobile) {
            this.callPhoneNumber(this.phoneList[0].mobile);
        }
    }

    /**
     * 拨打电话
     */
    callPhoneNumber(mobilePhone) {
        // this.callNumber.callNumber(mobilePhone, true).then(() => {
        //     this.clientNoteEditProvider.saveNote({
        //         type: 2,
        //         noteType: 3,
        //         content: "拨打电话",
        //         contentType: 1,
        //         clientNumber: this.currentClientNum
        //     }).subscribe(() => {
        //     }, error => {
        //         console.log('记录日志失败')
        //     });
        // }).catch(() => console.log('没打通'));
        console.log(mobilePhone);
        this.callNumberService.makeCall(mobilePhone,
            this.callNumberService.initClientNoteLog(this.currentClientNum),
            true,
            this.callNumberService.initFollowStateLog(this.currentClientNum), null, () => {
                this.getProgressList();
            });
    }

    /**
     *  返回
     */
    backToProPage() {
        this.navCtrl.pop(null);
    }

    // 跳转至编辑
    goToEdit() {
        if (this.clientId == undefined)
            this.clientId = 1;
        this.navCtrl.push('ExtensionEidtPage', {
            data: this.clientsData
        });
        console.log(this.clientId)
    }

    // 跳转至客户笔记
    goToNote(currentClientNum) {
        let base:BaseInfo=new BaseInfo();
        base.clientId=currentClientNum;
        this.navCtrl.push('ClientNoteListPage', {
            clientNum: currentClientNum,
            base:base
        })
    }

    /**
     * 确认框
     *
     * @private
     * @param {any} msg 询问的消息
     * @param {any} okCallback 用户点击确定后的回调
     * @param {any} cancelCallback 用户点击取消后的回调
     * @memberof ScheduleAddPage
     */
    showConfirm(msg, okCallback, cancelCallback) {
        if (this.alertObj) return;
        this.alertObj = this.alertCtrl.create({
            enableBackdropDismiss: false,
            message: msg,
            buttons: [{
                text: this.curStrResource.StrCancel,
                handler: cancelCallback
            }, {
                text: this.curStrResource.StrOk,
                handler: okCallback
            }]
        });
        this.alertObj.onDidDismiss(() => this.alertObj = null);
        this.alertObj.present();
    }

    // 金额格式化
    private moneyFormat(str) {
        return InsuredClientDetailProvider.transNum(str);
    }

    // 确定客户等级
    private getClientLevel(str) {
        return this.clientDetailProvider.getClientLevel(str);
    }
}
